<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>汽车入场模拟扫描</title>
    <link rel="stylesheet" href="/static/assets/css/layui.css" media="all">
    <script src="/static/assets/jquery.min.js"></script>
    <style>
        #emptyParkPlace {
            background: url("/static/assets/images/car.jpg");
        }

        #tips2 {
            background: url("/static/assets/images/bg01.jpg");
        }
    </style>
</head>
<body>
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-xs6">
            <div class="layui-carousel" lay-filter="test1" id="test2" style="margin-top:50px;">
                <div carousel-item="">
                    <div id="emptyParkPlace" style="font-size: 24px;text-align: center;color: red">

                    </div>
                    <div id="tips2"></div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs6">
            <input type="hidden" name="images" class="image">
            <div class="layui-form-item">
                <label class="layui-form-label ">入场扫描:</label>
                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="test1">入场扫描</button>
                    <div class="layui-upload-list">
                        <img style="width: 550px;height: 420px" class="layui-upload-img" id="demo1">
                        <p id="demoText"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/static/assets/layui.js"></script>
<script>
    //获得video摄像头区域
    video = document.getElementById("video");

    function getMedia() {
        var constraints = {
            video: {width: 500, height: 500},
            audio: true
        };
        /*
        这里介绍新的方法:H5新媒体接口 navigator.mediaDevices.getUserMedia()
        这个方法会提示用户是否允许媒体输入,(媒体输入主要包括相机,视频采集设备,屏幕共享服务,麦克风,A/D转换器等)
        返回的是一个Promise对象。
        如果用户同意使用权限,则会将 MediaStream对象作为resolve()的参数传给then()
        如果用户拒绝使用权限,或者请求的媒体资源不可用,则会将 PermissionDeniedError作为reject()的参数传给catch()
        */
        var promise = navigator.mediaDevices.getUserMedia(constraints);
        promise.then(function (MediaStream) {
            video.srcObject = MediaStream;
            video.play();
        }).catch(function (PermissionDeniedError) {
            console.log(PermissionDeniedError);
        })
    }

    var url

    function takePhoto() {
        //获得Canvas对象
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, 500, 500);
        console.log(document.getElementById('canvas').toDataURL())
        url = document.getElementById('canvas').toDataURL()
        $('#demo1').attr("src", url)
        var blob = dataURLtoBlob(url);
        var file = blobToFile(blob, new Date().toString());
        console.log(file)
        closeMedia()
        // $.ajax({
        //     url: '/user/upload',
        //     type: 'post',
        //     data: {file: url},
        //     dataType: 'json',
        //     success: function (res) {
        //         console.log(res)
        //     },
        //     error: function (res) {
        //
        //     }
        // })
    }

    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});
    }

    //将blob转换为file
    function blobToFile(theBlob, fileName) {
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
    }

    //调用


    function closeMedia() {
        var stream = document.getElementById('video').srcObject;
        var tracks = stream.getTracks();

        tracks.forEach(function (track) {
            track.stop();
        });

        document.getElementById('video').srcObject = null;
    }
</script>
<script>
    $(function () {
        layui.use(['upload', 'layer', 'carousel'], function () {
            var upload = layui.upload;
            var layer = layui.layer
            var carousel = layui.carousel
            //改变下时间间隔、动画类型、高度
            carousel.render({
                elem: '#test2'
                , interval: 2000
                , anim: 'fade'
                , height: '420px'
                , width: '550px'
            });
            $.ajax({
                url: "/parkPlace/emptyCount",
                type: "post",
                dataType: "json",
                data: {},
                success: function (res) {
                    console.log(res)
                    $("#emptyParkPlace").append("本停车场还剩余" + res.data.emptyParkPlace + "个车位")
                },
                error: function (data) {

                }
            })
            //普通图片上传
            var uploadInst = upload.render({
                elem: '#test1'
                , url: '/upload/show'
                , accept: 'images'
                , size: 50000
                , before: function (obj) {
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result);
                    });
                }
                , done: function (res) {
                    var filePath = res.data.filePath
                    //如果上传失败
                    if (res.code === 0) {
                        return layer.msg('上传失败');
                    } else {
                        //上传成功
                        var demoText = $('#demoText');
                        demoText.html('<span style="color: #4cae4c;">上传成功</span>');

                        var fileupload = $(".image");
                        fileupload.attr("value", res.data.src);
                        console.log(fileupload.attr("value"));
                        $.ajax({
                            url: "/scanCarNum",
                            type: "post",
                            dataType: "json",
                            data: {imgUrl: filePath},
                            success: function (res) {
                                console.log(res)
                                var carNum = res.data.carNum.number
                                $.ajax({
                                    url: "/accessInfo/add",
                                    type: "post",
                                    contentType: "application/json",
                                    dataType: "json",
                                    data: JSON.stringify({carNum: carNum, inImg: filePath}),
                                    success: function (res) {
                                        layer.open({
                                            type: 1,
                                            skin: 'layui-layer-demo', //样式类名
                                            closeBtn: 0, //不显示关闭按钮
                                            anim: 2,
                                            area: ['600px','400px'],
                                            shadeClose: true, //开启遮罩关闭
                                            content: "<p style='font-size: 48px'>车牌号：" + carNum + "</p><br/>"
                                                + "<p  style='font-size: 48px'>车辆类型：" + res.data.type + "</p><br/>" +
                                                "<p  style='font-size: 48px'>您的停车位是：" + res.data.parkPlace + "</p>"
                                        });
                                    }
                                })
                            },
                            error: function (res) {
                            }

                        })
                    }

                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });


        });
    })

</script>
</body>
</html>
